package chapter3.homework;

import java.io.*;
import java.util.Scanner;

/**
 * @Project ：learn_java
 * @File ：Q7.java
 * @IDE ：IntelliJ IDEA
 * @Author ：自由如风间
 * @Date ：2025/3/3 19:54
 * @Description ：For study.
 */

public class Q7 {
    public static void main(String[] args) throws IOException, FileNotFoundException {
        String path = "testIO\\words.txt";

        File file = new File(path);

        // 如果文件不存在则创建文件
        if (!file.exists()) {
            // 创建文件
            try {
                boolean newFile = file.createNewFile();
                if (newFile) {
                    System.out.println("文件创建成功");
                } else {
                    System.out.println("文件创建失败");
                    return;
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        Scanner scanner = new Scanner(System.in);

        // printStream写入
        try (FileOutputStream fos = new FileOutputStream(file);
             PrintStream ps = new PrintStream(fos, true);
        ) {
            System.out.println("请输入三行话：");

            String[] inputLines = new String[3];
            for (int i = 0; i < 3; i++) {
                System.out.print("第 " + i + " 行：");
                // 读取用户输入的一行内容
                inputLines[i] = scanner.nextLine();
                // 打印用户输入的内容
                ps.println(inputLines[i]);
            }

        }

        // scanner读取
        try (Scanner fileScanner = new Scanner(file)) {
            System.out.println("\nwords.txt 文件中的内容如下：");
            int lineNumber = 1;
            while (fileScanner.hasNextLine()) {
                String line = fileScanner.nextLine();
                System.out.println("第 " + lineNumber + " 行: " + line);
                lineNumber++;
            }
        } catch (FileNotFoundException e) {
            System.err.println("无法找到 words.txt 文件: " + e.getMessage());
        }

        scanner.close();
    }
}
